package com.excesys.exsecs.access.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.excesys.exsecs.access.dto.AccessBuildingsDTO;
import com.excesys.exsecs.access.entity.AccessBuildings;
import com.excesys.exsecs.access.mapper.AccessBuildingsMapper;
import com.excesys.exsecs.access.service.AccessBuildingsService;
import com.excesys.exsecs.access.vo.AccessBuildingsExcelVO;
import com.excesys.exsecs.admin.api.entity.SysAreaEntity;
import com.excesys.exsecs.admin.service.SysAreaService;
import com.excesys.exsecs.app.api.entity.AppUser;
import com.excesys.exsecs.common.core.util.MsgUtils;
import com.excesys.exsecs.common.core.util.R;
import com.excesys.exsecs.common.excel.vo.ErrorMessage;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.validation.BindingResult;

import java.text.DecimalFormat;
import java.text.Format;
import java.text.ParseException;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 区域管理-建筑管理
 *
 * @author lxc
 * @date 2024-09-13 11:48:31
 */
@Service
@RequiredArgsConstructor
public class AccessBuildingsServiceImpl extends ServiceImpl<AccessBuildingsMapper, AccessBuildings>
        implements AccessBuildingsService {

    private final SysAreaService sysAreaService;

    @Override
    public IPage<AccessBuildingsDTO> queryPage(Page page, AccessBuildingsDTO buildDTO) {
        IPage<AccessBuildingsDTO> ipage = this.baseMapper.queryPage(page, buildDTO);
        if (ipage.getTotal() > 0) {
            for(AccessBuildingsDTO dto : ipage.getRecords()){
                getAreaCode(dto);
            }
        }
        return ipage;
    }

    @Override
    public R importBuildings(List<AccessBuildingsExcelVO> excelVOList, BindingResult bindingResult) {
        // 通用校验获取失败的数据
        List<ErrorMessage> errorMessageList = (List<ErrorMessage>) bindingResult.getTarget();
        // 个性化校验逻辑
        List<AccessBuildings> bamSBuildings = this.list();

        int sucess = 0;
        int fail = 0;
        // 执行数据插入操作 组装 RoleDto
        for (AccessBuildingsExcelVO excel : excelVOList) {

            Set<String> errorMsg = new HashSet<>();

            boolean existSBuildings = bamSBuildings.stream()
                    .anyMatch(buildings -> excel.getBuildingsId().equals(buildings.getBuildingsId()));

            if (existSBuildings) {
                errorMsg.add(MsgUtils.getMessage("bm.bamsbuildings.code.existing", excel.getBuildingsId()));
            }

            // 数据合法情况
            if (CollUtil.isEmpty(errorMsg)) {
            }
            else {
                // 数据不合法情况
                errorMessageList.add(new ErrorMessage(excel.getLineNum(), errorMsg));
            }
            int num = insertBuildings(excel);
            if (num == 1) {
                fail++;
            }
            else {
                sucess++;
            }
        }
        if (CollUtil.isNotEmpty(errorMessageList)) {
            return R.failed(errorMessageList);
        }
        return R.ok(sucess, "成功导入数量" + sucess + "。" + "存在" + fail + "重复");
    }

    private int insertBuildings(AccessBuildingsExcelVO excel) {
        AccessBuildings bamSBuilding = new AccessBuildings();
        List<AccessBuildings> bamSBuildings = baseMapper.selectList(
                Wrappers.<AccessBuildings>lambdaQuery().eq(AccessBuildings::getBuildingsId, excel.getBuildingsId()));
        if (bamSBuildings.size() <= 0) {
            bamSBuilding.setBuildingsId(excel.getBuildingsId());
            bamSBuilding.setBuildingsCn(excel.getBuildingsCn());
            bamSBuilding.setBuildingsCs(excel.getBuildingsCs());
            bamSBuilding.setBuildingsDz(excel.getBuildingsDz());
            bamSBuilding.setBuildingsEn(excel.getBuildingsEn());
            bamSBuilding.setBuildingsCx(excel.getBuildingsCx());
            bamSBuilding.setBuildingsMj(excel.getBuildingsMj());
            bamSBuilding.setBuildingsQys(excel.getBuildingsQys());
            bamSBuilding.setBuildingsYt(excel.getBuildingsYt());
            bamSBuilding.setBuildingsYydw(excel.getBuildingsYydw());
            bamSBuilding.setRemark(excel.getRemark());
            this.save(bamSBuilding);
            return 0;
        }
        else {
            return 1;
        }
    }

    @Override
    public List<AccessBuildingsExcelVO> listBuildings(AccessBuildingsDTO buildingsDTO) {
        List<AccessBuildings> bamSBuildings = this.list(buildQueryWrapper(buildingsDTO));
        // 转换成execl 对象输出
        return bamSBuildings.stream().map(buildings -> {
            AccessBuildingsExcelVO bamAAssetSBuildingsExcelVO = new AccessBuildingsExcelVO();
            BeanUtil.copyProperties(buildings, bamAAssetSBuildingsExcelVO);
            return bamAAssetSBuildingsExcelVO;
        }).collect(Collectors.toList());
    }

    @Override
    public LambdaQueryWrapper buildQueryWrapper(AccessBuildingsDTO buildingsDTO) {
        // 定义查询条件
        LambdaQueryWrapper<AccessBuildingsDTO> wrapper = Wrappers.<AccessBuildingsDTO>lambdaQuery()
                .like(StrUtil.isNotBlank(buildingsDTO.getBuildingsCn()), AccessBuildingsDTO::getBuildingsCn,
                        buildingsDTO.getBuildingsCn())
                .eq(StrUtil.isNotBlank(buildingsDTO.getBuildingsDz()), AccessBuildingsDTO::getBuildingsDz,
                        buildingsDTO.getBuildingsDz())
                .eq(StrUtil.isNotBlank(buildingsDTO.getBuildingsEn()), AccessBuildingsDTO::getBuildingsEn,
                        buildingsDTO.getBuildingsEn())
                .eq(StrUtil.isNotBlank(buildingsDTO.getBuildingsYydw()), AccessBuildingsDTO::getBuildingsYydw,
                        buildingsDTO.getBuildingsYydw())
                .eq(StrUtil.isNotBlank(buildingsDTO.getBuildingsYt()), AccessBuildingsDTO::getBuildingsYt,
                        buildingsDTO.getBuildingsYt())
                .eq(StrUtil.isNotBlank(buildingsDTO.getBuildingsId()), AccessBuildingsDTO::getBuildingsId,
                        buildingsDTO.getBuildingsId());

        if (ArrayUtil.isNotEmpty(buildingsDTO.getQueryTime())) {
            // 根据时间轴查询 创建时间
            wrapper.ge(AccessBuildingsDTO::getCreateTime, buildingsDTO.getQueryTime()[0])
                    .le(AccessBuildingsDTO::getCreateTime, buildingsDTO.getQueryTime()[1]);
        }
        // wrapper.orderByDesc(BamSBuildingsDTO::getSort);
        return wrapper;
    }

    @Override
    public String GetBuildingCodeBy(String code, int level, String suffix) throws ParseException {
        StringBuffer fc = new StringBuffer();
        for (int i = 0; i < level; i++) {
            // fc.concat("0");
            fc.append("0");
        }
        String fccode = "";
        String fl = code + suffix;
        List<AccessBuildings> sBuildings = baseMapper.selectList(Wrappers.<AccessBuildings>lambdaQuery()
                .like(AccessBuildings::getBuildingsId, fl).orderByDesc(AccessBuildings::getBuildingsId));
        if (sBuildings.size() > 0) {
            int si = sBuildings.get(0).getBuildingsId().length();
            int fi = fl.length();
            String scode = sBuildings.get(0).getBuildingsId().replace(fl, "");
            // scode = scode.replace(suffix, "");
            Format f = new DecimalFormat(fc.toString());
            Long ij = (Long) f.parseObject(scode);
            ij = ij + 1;
            fccode = fl + f.format(ij);
        }
        else {
            Format f = new DecimalFormat(fc.toString());
            Long ij = (Long) f.parseObject(fc.toString());
            ij = ij + 1;
            fccode = fl + f.format(ij);
        }
        return fccode;
    }

    private AccessBuildingsDTO getAreaCode(AccessBuildingsDTO dto){
        //行政编码
        if (dto.getVarCode() == null){
            dto.setVarCode(dto.getAdCode());
        }
        SysAreaEntity entity = sysAreaService.getOne(Wrappers.<SysAreaEntity>lambdaQuery().eq(SysAreaEntity::getAdcode, dto.getVarCode()));
        if (ObjectUtil.isNotEmpty(entity)) {
            switch (entity.getAreaType()) {
                case "1":
                    dto.setProvinceCode(entity.getAdcode());
                    dto.setProvinceType(entity.getAreaType());
                    dto.setVarCode(entity.getPid());
                    dto = getAreaCode(dto);
                    break;
                case "2":
                    dto.setCityCode(entity.getAdcode());
                    dto.setCityType(entity.getAreaType());
                    dto.setVarCode(entity.getPid());
                    dto = getAreaCode(dto);
                    break;
                case "3":
                    dto.setDistrictCode(entity.getAdcode());
                    dto.setDistrictType(entity.getAreaType());
                    dto.setVarCode(entity.getPid());
                    dto = getAreaCode(dto);
                    break;
                case "4":
                    dto.setStreetCode(entity.getAdcode());
                    dto.setStreetType(entity.getAreaType());
                    dto.setVarCode(entity.getPid());
                    dto = getAreaCode(dto);
                    break;
                default:
                    break;
            }
        }
        return dto;
    }
}